import { ApplyVip, GetUserInfo, UserVip } from '@/api/user';
import useCustomerService from '@/components/useCustomerService';
import { Button, Checkbox, Icon, Popup } from '@antmjs/vantui';
import { Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import dayjs from 'dayjs';
import { useMemo, useState } from 'react';
import { useRequest } from 'taro-hooks';
import { TemplateMessage } from 'types/user';

export default function useRecharge() {
  const [show, setShow] = useState<boolean>(false);
  const { data: user, refresh: refreshUser } = useRequest(GetUserInfo, {
    cacheKey: 'get:user:info',
  });

  const [vipId, setVipId] = useState<number>();
  const [agree, setAree] = useState<boolean>(false);

  const { runAsync: runApplyAsync, loading } = useRequest(ApplyVip, {
    manual: true,
  });

  const { data, refresh: refreshUserVipStatus } = useRequest(UserVip, {
    onSuccess: function (res) {
      res?.list?.[0] && setVipId(res?.list[0].id);
    },
  });

  const gold = useMemo(() => data?.list?.[0], [data]);
  const silver = useMemo(() => data?.list?.[1], [data]);

  const { renderNode: renderServiceNode, open: openService } =
    useCustomerService();

  function renderNode() {
    return (
      <>
        <Popup
          show={show}
          round
          position='bottom'
          safeAreaInsetBottom
          className='p-4'
          style={{
            overflow: 'initial',
          }}
          onClose={() => setShow(false)}
        >
          <Icon
            name='close'
            onClick={() => setShow(false)}
            className=' absolute right-2 -top-[90px] text-3xl text-white'
          />
          <Text className=' text-lg font-bold text-black block mb-2'>
            开通会员
          </Text>
          <Text className=' text-xs text-gary4'>
            会员所在公司签订协议，可开专票。
          </Text>

          <View
            className='py-8 pb-4 border-[2px] border-solid border-[rgba(70,109,180,0.2)] rounded-lg mb-4 mt-8 relative'
            style={{
              background:
                'linear-gradient(180deg, rgba(179,199,248,0.42) 0%, rgba(196,213,253,0.48) 44%, rgba(213,223,249,0.17) 100%)',
            }}
          >
            <View
              className='w-[268px] h-[58px] leading-[52px] bg-cover absolute -top-[20px] left-1/2 -translate-x-1/2  text-black font-bold text-center text-lg'
              style={{
                backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/title-bg-1.png)`,
              }}
            >
              会员权益
            </View>

            {/* 金卡 */}
            {gold && (
              <View
                onClick={() => setVipId(gold.id)}
                className={classNames(
                  `mx-auto w-[640px] h-[188px] relative border-solid border-4 rounded-lg bg-cover`,
                  {
                    'border-warn': gold?.id === vipId,
                    'border-transparent': gold.id !== vipId,
                  }
                )}
                style={{
                  backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/jinka.png)`,
                  backgroundSize: '100% 100%',
                  backgroundRepeat: 'no-repeat',
                }}
              >
                {gold.recommend && (
                  <View
                    className='w-[96px] h-[48px] bg-cover absolute left-0 -top-3'
                    style={{
                      backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-rec-1.svg)`,
                    }}
                  ></View>
                )}

                <Text className=' text-[#9F5300] text-[48px] absolute left-[46px] top-[44px] font-bold leading-none'>
                  ￥{gold?.price}
                </Text>
                <View className=' bg-[rgba(255,255,255,.4)] text-[#9F5300] rounded-full px-2 py-1 absolute left-[280px] top-[46px] text-[20px]'>
                  兑换{gold.beans}帮豆
                </View>
              </View>
            )}

            {/* 银卡 */}
            {silver && (
              <View
                onClick={() => setVipId(silver.id)}
                className={classNames(
                  `mx-auto w-[640px] h-[188px] relative mt-3 border-solid border-4 rounded-lg bg-cover`,
                  {
                    'border-warn': silver?.id === vipId,
                    'border-transparent': silver.id !== vipId,
                  }
                )}
                style={{
                  backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/yinka.png)`,
                  backgroundSize: '100% 100%',
                  backgroundRepeat: 'no-repeat',
                }}
              >
                {silver.recommend && (
                  <View
                    className='w-[96px] h-[48px] bg-cover absolute left-0 -top-3'
                    style={{
                      backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-rec-1.svg)`,
                    }}
                  ></View>
                )}

                <Text className=' text-[#2A748D] text-[48px] absolute left-[46px] top-[44px] font-bold leading-none'>
                  ￥{silver?.price}
                </Text>
                <View className=' bg-[rgba(255,255,255,.4)] text-[#2A748D] rounded-full px-2 py-1 absolute left-[280px] top-[46px] text-[20px]'>
                  兑换{silver.beans}帮豆
                </View>
              </View>
            )}
          </View>

          <View className=' flex items-center text-xs flex-wrap'>
            <Checkbox
              iconSize={32}
              value={agree}
              onChange={(e) => setAree(e.detail)}
            >
              开通会员即表示您已同意及
            </Checkbox>
            <Text
              className=' text-primary'
              onClick={() => {
                Taro.navigateTo({ url: `/pages/rules` });
              }}
            >
              《臻会帮会员服务协议》
            </Text>
            及
            <Text
              className=' text-primary'
              onClick={() => {
                Taro.navigateTo({ url: `/pages/charge` });
              }}
            >
              《权益说明》
            </Text>
          </View>

          <Button
            className=' mt-2'
            type='primary'
            size='large'
            disabled={!agree || data?.applying || Boolean(user?.vip)}
            loading={loading}
            onClick={async () => {
              //@ts-ignore
              await Taro.requestSubscribeMessage({
                tmplIds: [TemplateMessage.余额变动提醒],
              });

              if (!vipId) return;
              await runApplyAsync({
                vip: vipId,
              });

              Taro.showToast({ title: '提交成功' });
              setShow(false);
              refreshUserVipStatus();
              refreshUser();
            }}
          >
            {data?.applying
              ? `您提交的会员申请正在审核中`
              : user?.vip
              ? `您已是${user.vip === 1 ? '金' : '银'}卡会员`
              : '开通会员'}
          </Button>
          <View className=' text-xs text-center text-gary4 mt-2'>
            {(user?.vip && (
              <Text className='text-[20px]'>
                当前会员有效期至{' '}
                {user.vip_end_time &&
                  dayjs(user.vip_end_time).format('YYYY-MM-DD')}{' '}
                过期后可再次开通
              </Text>
            )) || (
              <>
                提交申请后，
                <Text
                  className=' font-bold text-primary'
                  onClick={() => openService()}
                >
                  平台客服
                </Text>
                将联系您完成协议签订
              </>
            )}
          </View>
        </Popup>

        {renderServiceNode()}
      </>
    );
  }
  return {
    renderNode,
    open: () => setShow(true),
  };
}
